package com.yvon.boot.log.config;

import cn.hutool.json.JSONUtil;
import com.yvon.boot.log.aspect.LogAspect;
import com.yvon.boot.log.event.LogListener;
import com.yvon.boot.log.feign.LogFeignClient;
import com.yvon.boot.log.monitor.PointUtil;
import com.yvon.boot.log.properties.LogProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * 日志配置
 *
 * @author : Yvon
 * @since : 2022-05-12
 */
@EnableAsync
@Configuration
@RequiredArgsConstructor
@ConditionalOnWebApplication
@ConditionalOnProperty(prefix = "maple.log", name = {"enabled"}, havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(value = LogProperties.class)
@EnableFeignClients(basePackages = {"com.yvon.boot.log.feign"})
@Slf4j
public class LogConfig {

    @Autowired
    private LogFeignClient logFeignClient;

    @Bean
    @ConditionalOnMissingBean
    public LogAspect sysLogAspect(ApplicationContext applicationContext) {
        log.info("启动日志拦截器...");
        return new LogAspect(applicationContext);
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnExpression("${maple.log.enabled:true} && 'LOGGER'.equals('${maple.log.type}')")
    public LogListener logPointListener() {
        return new LogListener((log) -> {
            PointUtil.info("0", "OPT_LOG", JSONUtil.toJsonStr(log));
        });
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnExpression("${maple.log.enabled:true} && 'DB'.equals('${maple.log.type:DB}')")
    public LogListener logDbListener() {
        return new LogListener((log) -> {
            logFeignClient.set(log);
        });
    }

}
